package com.atguigu.gulimall.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.authserver.cons.OauthConst;
import com.atguigu.gulimall.authserver.feign.memberFeignService;
import com.atguigu.gulimall.authserver.vo.GiteeAccessToken;
import com.atguigu.gulimall.authserver.vo.GiteeUserInfo;
import com.atguigu.common.vo.MemberEntityVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class Oauth2Controller {

    @Autowired
    memberFeignService memberFeignService;

    //    @ResponseBody

    //    http://auth.gulimall.com/oauth2.0/gitee/success
    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession httpSession) throws Exception {
//        HashMap<String, Object> paraMap = new HashMap<>();
//        paraMap.put("code",code);
//        System.out.println("回调收集来的code为:"+code);
//        return code;
        Map<String, String> bodys = new HashMap<>();
        bodys.put("grant_type", "authorization_code");
        bodys.put("code", code);
        bodys.put("client_id", "932392466e048f7662a7a85a177fe802bbad5939a72a41bbd6dccb35e5c26186");
        bodys.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        bodys.put("client_secret", "cf882e621119dce6d67acb210e751e67c7a5d97141390cdcfa81762b73b44006");
        //1.根据code换取GiteeAccessToken;
        HttpResponse response_GiteeAccesstoken = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap(), new HashMap(), bodys);

        //处理返回值
        if (response_GiteeAccesstoken.getStatusLine().getStatusCode() == 200) {
            //获取到了GiteeAccessToken
            MemberEntityVo memberEntityVo = new MemberEntityVo();
            String tokenJson = EntityUtils.toString(response_GiteeAccesstoken.getEntity());
            JSONObject jsonObject = JSON.parseObject(tokenJson);
            System.out.println(jsonObject);
            GiteeAccessToken token = JSON.parseObject(tokenJson, GiteeAccessToken.class);
            //根据Token，通过查询Gitee Open Api获取用户信息
            Map<String, String> query = new HashMap<>();
            query.put("access_token", token.getAccess_token());
            memberEntityVo.setAccess_token(token.getAccess_token());
            memberEntityVo.setExpiresIn(token.getExpires_in() + "");
            try {
                HttpResponse response_userInfo = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap(), query);
                String giteeUserInfoJson = EntityUtils.toString(response_userInfo.getEntity());
                GiteeUserInfo giteeUserInfo = JSON.parseObject(giteeUserInfoJson, GiteeUserInfo.class);
                System.out.println("giteeUserInfo:" + giteeUserInfo);
                memberEntityVo.setSocialUid(giteeUserInfo.getId() + "");
                memberEntityVo.setNickname(giteeUserInfo.getName());
                //设置编号
//                memberEntityVo.setId(giteeUserInfo.getId());
            } catch (Exception exception) {

            }

            //登录或者注册这个社交用户
            //1.当前用户如果是第一次进入网站，就自动注册（为当前社交用户生成一个会员信息账号，以后这个社交账号就对应指定的会员）

            R r = memberFeignService.dealSocialLogin(memberEntityVo);
            if (r.getCode() == 0) {
                //注册或者登录成功
                TypeReference<MemberEntityVo> typeReference = new TypeReference<MemberEntityVo>() {
                };
                //获取远程注册的结果
                MemberEntityVo entityVo = r.getData(typeReference);
                //放入session中
                httpSession.setAttribute(OauthConst.LOGIN_SESSION_KEY, entityVo);
                System.out.println("远程返回的结果:" + entityVo);
                //2.登录成功后跳回首页
                return "redirect:http://gulimall.com";

            } else {
                return "redirect:http://auth.gulimall.com/login.html";

            }

        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }
}
